<template>
  <view class="home-container">
    <!-- Header section with status bar height -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
    <view class="header">
      <text class="title">云知茶</text>
      <view class="header-buttons">
        <view class="more-btn">
          <text class="dot"></text>
          <text class="dot"></text>
          <text class="dot"></text>
        </view>
        <view class="circle-btn"></view>
      </view>
    </view>

    <!-- Swiper/Banner section -->
    <swiper class="banner-swiper" circular indicator-dots autoplay>
      <swiper-item v-for="(item, index) in carouselList" :key="index" @click="handleCarouselClick(item)">
        <image class="swiper-image" :src="formatImageUrl(item.imageUrl)" mode="aspectFill"
               @error="handleImageError($event, item)"></image>
      </swiper-item>
      <swiper-item v-if="carouselList.length === 0">
        <image class="swiper-image" src="/static/images/home/swiper1.png" mode="aspectFill"></image>
      </swiper-item>
    </swiper>

    <view class="under" style="background-image: url('/static/images/home-logo2.png');">
      <!-- Immediate Order section -->
      <view class="order-section" @click="navigateToMenu" hover-class="order-section-hover">
        <view class="order-content">
          <image class="order-left-image" src="/static/images/home/immediate-order-left.jpg" mode="aspectFit"></image>
          <view class="order-text">
            <text class="order-title">立即点餐</text>
            <text class="order-desc">手机点 到店取 免排队</text>
          </view>
        </view>
        <view class="order-arrow">
          <view class="arrow-right"></view>
        </view>
      </view>

      <!-- Feature options section -->
      <view class="feature-options">
        <view class="feature-item" @tap="toggleAIChat">
          <image
          class="feature-icon star-icon" src="/static/images/home/AI.png" mode="aspectFit"/>
          <image class="feature-icon " src="/static/images/home/star.png" mode="aspectFit"></image>
          <text class="feature-text">今天喝点啥</text>
        </view>
        <view class="feature-item" @tap="navigateToMenu">
          <image class="feature-icon" src="/static/images/home/recommend.png" mode="aspectFit"></image>
          <text class="feature-text">人气推荐</text>
        </view>
        <view class="feature-item" @tap="showContactInfo">
          <image class="feature-icon" src="/static/images/home/welcome-phone.png" mode="aspectFit"></image>
          <text class="feature-text">欢迎致电</text>
        </view>
      </view>

    </view>


    <!-- AI聊天弹窗 -->
    <view class="ai-chat-popup" :class="{ 'show': showAIChat }">
      <view class="chat-header">
        <text>智能推荐</text>
        <text class="close-btn" @tap="toggleAIChat">×</text>
      </view>

      <scroll-view class="chat-content" scroll-y scroll-with-animation
                   :scroll-top="scrollTop">
        <view class="chat-messages">
          <view v-for="(msg, index) in chatMessages"
                :key="index"
                :class="['message', msg.type]">
            <text>{{ msg.content }}</text>
          </view>
          <!-- 加载动画 -->
          <view v-if="isLoading" class="message ai loading">
            <view class="dot-loading">
              <view class="dot"></view>
              <view class="dot"></view>
              <view class="dot"></view>
            </view>
          </view>
        </view>
      </scroll-view>

      <view class="chat-input">
        <input type="text"
               v-model="userInput"
               placeholder="请输入您的问题"
               :disabled="isLoading"
               @confirm="sendMessage"/>
        <button @tap="sendMessage"
                :disabled="isLoading || !userInput.trim()">
          发送
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import {getCarouselList} from '@/api/carousel'
import config from '@/config.js'
import {getAIRecommendation} from '@/api/ai.js';
// 在组件外添加全局日志，确保页面加载即可见
console.log('==== HOME PAGE SCRIPT LOADED ====');

export default {
  data() {
    // 添加控制台日志，验证data函数执行
    console.log('==== HOME PAGE DATA FUNCTION EXECUTING ====');
    return {
      goods: null, // 引入静态数据
      userInput: '',
      chatMessages: [],
      isLoading: false,
      highlightedGoods: [], // 改为数组存储推荐的商品名称
      showAIChat: false,
      statusBarHeight: 20, // Default value
      carouselList: [], // 轮播图列表
      baseImageUrl: config.baseUrl + '/static/image/', // 基础图片URL
      config: config, // 配置信息
      debugLogs: [] // 新增：存储日志以便在UI中显示
    }
  },
  onLoad() {
    this.addDebugLog('home.vue onLoad 开始');
    console.log('HOME PAGE ONLOAD - START');

    // 使用新的推荐API获取状态栏高度
    try {
      // 替换过时的wx.getSystemInfoSync
      const res = uni.getWindowInfo ? uni.getWindowInfo() : uni.getSystemInfoSync();
      this.statusBarHeight = res.statusBarHeight;
      this.addDebugLog('获取状态栏高度: ' + this.statusBarHeight);
    } catch (e) {
      console.error('获取状态栏高度失败:', e);
      this.addDebugLog('获取状态栏高度失败: ' + JSON.stringify(e));
      // Fallback to default value
    }

    // 增加延迟确保组件完全加载
    setTimeout(() => {
      // 获取轮播图数据
      this.addDebugLog('调用 getCarouselList (onLoad setTimeout)');
      console.log('HOME PAGE - CALLING CAROUSEL API FROM ONLOAD');
      this.getCarouselList();
    }, 800); // 增加延迟到800ms，给足够时间初始化

    this.addDebugLog('home.vue onLoad 完成');
    console.log('HOME PAGE ONLOAD - COMPLETE');
    this.init();
  },
  computed: {
    currentSeason() {
      const month = new Date().getMonth() + 1;
      if (month >= 3 && month <= 5) return '春';
      if (month >= 6 && month <= 8) return '夏';
      if (month >= 9 && month <= 11) return '秋';
      return '冬';
    }
  },
  // 页面每次显示时也尝试获取数据，确保数据最新
  onReady() {
    this.addDebugLog('home.vue onReady 开始');
    console.log('HOME PAGE ONREADY - START');

    // 在onReady中也尝试获取数据，确保组件已渲染完成
    this.addDebugLog('调用 getCarouselList (onReady)');
    this.getCarouselList();

    this.addDebugLog('home.vue onReady 完成');
    console.log('HOME PAGE ONREADY - COMPLETE');
  },

  onShow() {
    this.addDebugLog('home.vue onShow 开始');
    console.log('HOME PAGE ONSHOW - START');

    // 获取轮播图数据 - 只在onShow后延迟执行，避免与onLoad/onReady重复调用
    if (!this.carouselList || this.carouselList.length === 0) {
      setTimeout(() => {
        this.addDebugLog('调用 getCarouselList (onShow延迟调用)');
        this.getCarouselList();
      }, 500);
    }

    this.addDebugLog('home.vue onShow 完成');
    console.log('HOME PAGE ONSHOW - COMPLETE');
  },
  methods: {
    async init() {
      let that = this;
      that.$request('/config', 'get').then(result => {
        console.log('刷新配置信息:' + JSON.stringify(result.data));
        that.$store.commit('set_app_properties', result.data);
      });

      that.$request('/goods/getAllGoods', 'get').then(result => {
		console.log('11111111'+result)
        that.goods = result.data;
        that.sizeCalcState = false;
        uni.stopPullDownRefresh();
      });
    },
    // 添加日志辅助方法，同时在控制台和调试面板显示
    addDebugLog(message) {
      console.log(message);
      this.debugLogs.push({
        time: new Date().toLocaleTimeString(),
        message: message
      });
      // 限制日志数量
      if (this.debugLogs.length > 20) {
        this.debugLogs.shift();
      }
    },
    async sendMessage() {
      if (!this.userInput.trim() || this.isLoading) return;

      this.isLoading = true;
      // 添加用户消息
      this.chatMessages.push({
        type: 'user',
        content: this.userInput
      });

      try {
        // 获取所有商品名称
       const menuItems = this.goods.reduce((acc, item) => {
           if (!acc.includes(item.name)) {
               acc.push(item.name);
           }
           return acc;
       }, []);

        // 获取AI回复
        const aiResponse = await getAIRecommendation(
            this.userInput,
            menuItems,
            this.currentSeason
        );

        // 添加AI回复
        this.chatMessages.push({
          type: 'ai',
          content: aiResponse
        });

        // 高亮推荐的商品
        this.highlightRecommendedItems(aiResponse);

      } catch (error) {
        this.chatMessages.push({
          type: 'ai',
          content: error.message || '抱歉，推荐服务暂时出现问题，请稍后再试。'
        });
      } finally {
        this.isLoading = false;
        this.userInput = '';
        this.$nextTick(() => {
          this.scrollTop = 9999;
        });
      }
    },
    // 显示联系方式
    showContactInfo() {
      uni.showModal({
        title: '开发者信息',
        content: '姓名:王韩潇\n学号:2321200120\n联系方式:18523516303',
        showCancel: false,
        confirmText: '关闭'
      });
    },
    // 保存推荐商品到本地存储
    saveHighlightedGoods(goods) {
      try {
        uni.setStorageSync('highlightedGoods', JSON.stringify(goods));
        console.log('保存推荐商品成功');
      } catch (error) {
        console.error('保存推荐商品失败:', error);
      }
    },
    highlightRecommendedItems(aiResponse) {
      // 清空之前的推荐
      this.highlightedGoods = [];

      // 提取加粗的商品名称
      const matches = aiResponse.match(/\*\*(.*?)\*\*/g);
      if (matches) {
        matches.forEach(match => {
          // 去掉**符号
          const goodsName = match.replace(/\*\*/g, '');
          this.highlightedGoods.push(goodsName);
          this.saveHighlightedGoods(this.highlightedGoods)
        });
      }
    },
    toggleAIChat() {
      if (!this.showAIChat) {
        this.showAIChat = true;
        if (this.chatMessages.length === 0) {
          this.chatMessages.push({
            type: 'ai',
            content: `您好！我是您的智能推荐助手。现在是${this.currentSeason}季，请问需要什么帮助吗？`
          });
        }
      } else {
        // 等待动画完成后再隐藏
        setTimeout(() => {
          this.showAIChat = false;
        }, 300);
      }
    },
    // 获取轮播图列表
    async getCarouselList() {
      this.addDebugLog('开始获取轮播图数据');

      // 显示加载状态
      uni.showLoading({
        title: '加载中...',
        mask: true
      });

      try {
        // 打印API请求的基础URL，确保配置正确
        this.addDebugLog('API基础URL: ' + config.baseUrl);

        // 同时进行两种请求方式，使用Promise.allSettled确保即使一个失败另一个仍然执行
        const [directRequest, carouselRequest] = await Promise.allSettled([
          // 直接请求方式
          this.$request('/api/carousel/list', 'get').catch(err => {
            this.addDebugLog('直接API调用异常: ' + JSON.stringify(err));
            return null;
          }),

          // 通过carousel.js方式
          getCarouselList().catch(err => {
            this.addDebugLog('carousel.js调用异常: ' + JSON.stringify(err));
            return null;
          })
        ]);

        // 隐藏加载状态
        uni.hideLoading();

        // 记录直接请求的结果
        if (directRequest.status === 'fulfilled' && directRequest.value) {
          this.addDebugLog('直接API调用成功: ' + JSON.stringify(directRequest.value).substring(0, 100) + '...');
        } else {
          this.addDebugLog('直接API调用未成功完成');
        }

        // 处理carousel.js的请求结果
        if (carouselRequest.status === 'fulfilled' && carouselRequest.value) {
          const res = carouselRequest.value;
          this.addDebugLog('carousel.js调用成功: ' + JSON.stringify(res).substring(0, 100) + '...');

          if (res && res.code === 200) {
            this.carouselList = res.data || [];
            this.addDebugLog('轮播图数据处理成功，获取到' + this.carouselList.length + '个项目');

            // 如果获取到了数据，显示成功提示
            if (this.carouselList.length > 0) {
              uni.showToast({
                title: '加载成功',
                icon: 'success',
                duration: 1000
              });
            }
          } else {
            this.addDebugLog('轮播图API返回错误: ' + JSON.stringify(res));
            this.carouselList = [];
          }
        } else {
          // 尝试从直接请求中获取数据
          if (directRequest.status === 'fulfilled' && directRequest.value && directRequest.value.code === 200) {
            this.carouselList = directRequest.value.data || [];
            this.addDebugLog('从直接请求中获取数据成功，获取到' + this.carouselList.length + '个项目');
          } else {
            this.addDebugLog('两种请求方式均未获取到数据');
            this.carouselList = [];
          }
        }
      } catch (error) {
        // 隐藏加载状态
        uni.hideLoading();

        this.addDebugLog('轮播图获取异常: ' + JSON.stringify(error));
        console.error('轮播图获取异常:', error);
        this.carouselList = [];

        // 显示错误提示
        uni.showToast({
          title: '加载失败',
          icon: 'none',
          duration: 2000
        });
      }
    },

    // 格式化图片URL
    formatImageUrl(imagePath) {
      if (!imagePath) return '';
      // For absolute URLs that already have http/https, return as is
      if (imagePath.startsWith('http')) return imagePath;
      // For relative paths, ensure they're properly formatted
      return this.baseImageUrl + imagePath;
    },

    // 处理轮播图点击事件
    handleCarouselClick(item) {
      if (item && item.linkUrl) {
        // 如果有链接地址，则跳转
        uni.navigateTo({
          url: item.linkUrl
        });
      }
    },

    navigateToMenu() {
      uni.switchTab({
        url: '/pages/menu/menu'
      });
    },

    // 处理图片加载错误
    handleImageError(e, item) {
      this.addDebugLog('图片加载失败: ' + (item ? item.imageUrl : 'unknown'));
      console.error('图片加载失败:', e, '图片URL:', item ? item.imageUrl : 'unknown');
    }
  }
}
</script>

<style lang="scss">
@import './home.scss';

uni-modal .uni-modal__bd {
  white-space: pre-wrap;
}

.home-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100%;
}

.under {
  background-size: cover;
  background-position: center center;
  background-repeat: no-repeat;
  width: 100%;
  flex: 1;
  position: relative;
  display: flex;
  flex-direction: column;
  padding: 20rpx 20rpx 0 20rpx;
  margin-bottom: -30rpx;
}

.ai-chat-popup {
  position: fixed;
  right: 0rpx;
  top: 50%;
  transform: translateY(-50%) translateX(100%);
  width: 600rpx;
  height: 800rpx;
  background: #fff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.15);
  z-index: 99;
  display: flex;
  flex-direction: column;
  opacity: 0;
  transition: all 0.3s ease-in-out;

  &.show {
    transform: translateY(-50%) translateX(0);
    opacity: 1;
  }

  .chat-header {
    padding: 20rpx;
    border-bottom: 1rpx solid #eee;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .close-btn {
      font-size: 40rpx;
      color: #999;
      padding: 0 20rpx;
    }
  }

  .chat-content {
    flex: 1;
    // padding: 20rpx;
    overflow-y: auto;

    .chat-messages {
      .message {
        margin-bottom: 20rpx;
        padding: 20rpx;
        border-radius: 10rpx;
        max-width: 80%;

        &.user {
          background: #97AF13;
          color: #fff;
          margin-left: auto;
        }

        &.ai {
          background: #f5f5f5;
          color: #333;
        }

        &.loading {
          background: transparent;
          display: flex;
          justify-content: flex-start;
          padding: 10rpx 20rpx;

          .dot-loading {
            display: flex;
            align-items: center;
            gap: 8rpx;

            .dot {
              width: 12rpx;
              height: 12rpx;
              background: #97AF13;
              border-radius: 50%;
              animation: dotBounce 1.4s infinite ease-in-out;

              &:nth-child(1) {
                animation-delay: 0s;
              }

              &:nth-child(2) {
                animation-delay: 0.16s;
              }

              &:nth-child(3) {
                animation-delay: 0.32s;
              }
            }
          }
        }
      }
    }
  }

  .chat-input {
    padding: 20rpx;
    border-top: 1rpx solid #eee;
    display: flex;
    align-items: center;

    input {
      flex: 1;
      height: 70rpx;
      border: 1rpx solid #ddd;
      border-radius: 35rpx;
      padding: 0 30rpx;
      margin-right: 20rpx;
    }

    button {
      width: 120rpx;
      height: 70rpx;
      background: #97AF13;
      color: #fff;
      border-radius: 35rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;

      &:disabled {
        opacity: 0.6;
        cursor: not-allowed;
      }
    }
  }
}

.feature-item {
  position: relative; /* 添加相对定位 */
}

.star-icon {
  position: absolute;
  top: -30rpx;
  right: -10rpx;
  width: 60rpx !important;
  height: 60rpx !important;
}
</style> 